import logging

from sqlalchemy import text, distinct

from app.commons.config import get_current_time
from app.commons.redis_session import redis_con
from app.models.admin.admin import UserInfo
from app.models.admin.token_info import TokenInfo


def checkIfLogin(token):
    try:
        username=token.split("_")[0]
        login_time=int(token.split("_")[1])
        logging.warning("check user login, username=%s, last_login_time=%s"%(username,login_time))
        r = redis_con()
        userlist_cache=r.smembers("user_list")
        if username not in userlist_cache:
            users = UserInfo.query.with_entities(UserInfo.user_name).all()
            userlist = []
            for user in users:
                userlist.append(list(user)[0])
            if username not in userlist:
                logging.warning("user not existing or expired, username=%s, last_login_time=%s" % (username, login_time))
                return False
            r.sadd("user_list",username)
        if get_current_time('s')-login_time>86400*10:
            return False
        return username
    except:
        logging.warning("check user login error")
        return False
